package edu.ynu.se.xiecheng.achitectureclass.project.service;

import edu.ynu.se.xiecheng.achitectureclass.project.dao.DataDAO;
import edu.ynu.se.xiecheng.achitectureclass.project.po.entity.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Collections;

@Service
public class DataService {

    private static final Logger log = LoggerFactory.getLogger(DataService.class);

    @Autowired
    private DataDAO dataDAO;

    // 获取所有未删除的数据
    public List<Data> getAllData() {
        List<Data> dataList = dataDAO.findByIsDeletedFalse();
        if (dataList == null || dataList.isEmpty()) {
            log.warn("No active data found in the database.");
            return Collections.emptyList(); // 返回空列表
        }
        return dataList;
    }

    // 根据 serialId 获取未删除的数据
    public Data getDataBySerialId(String serialId) {
        Data data = dataDAO.findBySerialIdAndIsDeletedFalse(serialId);
        if (data == null) {
            log.warn("No active data found with serialId: {}", serialId);
            return null; // 返回 null 或自定义响应
        }
        return data;
    }

    // 逻辑删除数据（将 isDeleted 设置为 true）
    public void deleteDataBySerialId(String serialId) {
        Data data = dataDAO.findBySerialIdAndIsDeletedFalse(serialId);
        if (data == null) {
            log.warn("Data with serialId {} not found for deletion.", serialId);
            return; // 如果数据不存在，直接返回
        }
        data.setIsDeleted(true); // 逻辑删除
        dataDAO.save(data);
    }

    // 插入新数据
    public void insertData(Data data) {
        data.setTimestamp(LocalDateTime.now());
        data.setIsDeleted(false); // 默认未删除
        dataDAO.save(data);
    }

    // 更新数据
    public void updateData(String serialId, String boxNo, String name, Double value) {
        Data data = dataDAO.findBySerialIdAndIsDeletedFalse(serialId);
        if (data == null) {
            log.warn("Data with serialId {} not found for update.", serialId);
            return; // 如果数据不存在，直接返回
        }
        data.setBoxNo(boxNo);
        data.setName(name);
        data.setValue(value);
        data.setTimestamp(LocalDateTime.now());
        dataDAO.save(data);
    }

    // 根据 name 属性查询未删除的土壤数据
    public List<Data> getSoilDataByName(String name) {
        List<Data> dataList = dataDAO.findByNameAndIsDeletedFalse(name);
        if (dataList == null || dataList.isEmpty()) {
            log.warn("No active data found with name: {}", name);
            return Collections.emptyList(); // 返回空列表
        }
        return dataList;
    }
}